package util

import (
	"errors"
	"strconv"
	"time"
)

const (
	StdTimeFormat = "2006-01-02 15:04:05"
)

// ToUnix 将标准时间转换为时间戳
func ToUnix(format string) int64 {

	t, err := time.Parse("2006-01-02 15:04:05", format)
	if err != nil {
		return 0
	}
	return t.Unix()
}

// FormatNow 将现在的时间戳转换为标准时间
func FormatNow() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

// UnixToFormat 将时间戳转换为标准时间
func UnixToFormat(unix string) string {
	unixINT64, err := strconv.ParseInt(unix, 10, 64)
	if err != nil {
		return ""
	}
	format := time.Unix(unixINT64, 0).Format("2006-01-02 15:04:05")

	return format
}

func DateTimeConflict(s1, e1, s2, e2 string) bool {
	// s1 e1 s2 e2   s2>e1 sh>eo
	// s2 e2 s1 e1   s1>e2 so>eh
	if ToUnix(s2) <= ToUnix(e1) && ToUnix(s1) <= ToUnix(e2) {
		return true
	}
	return false
}

var (
	ErrInvalidTimeString = errors.New("invalid time string")
)

func BeforeThan(s1, s2 string) (bool, error) {
	t1, err := time.Parse(StdTimeFormat, s1)
	if err != nil {
		return false, ErrInvalidTimeString
	}
	t2, err := time.Parse(StdTimeFormat, s2)
	if err != nil {
		return false, ErrInvalidTimeString
	}

	return t1.Before(t2), nil
}

func AfterThan(s1, s2 string) (bool, error) {
	t1, err := time.Parse(StdTimeFormat, s1)
	if err != nil {
		return false, ErrInvalidTimeString
	}
	t2, err := time.Parse(StdTimeFormat, s2)
	if err != nil {
		return false, ErrInvalidTimeString
	}

	return t1.After(t2), nil
}

func Equal(s1, s2 string) (bool, error) {
	t1, err := time.Parse(StdTimeFormat, s1)
	if err != nil {
		return false, ErrInvalidTimeString
	}
	t2, err := time.Parse(StdTimeFormat, s2)
	if err != nil {
		return false, ErrInvalidTimeString
	}

	return t1.Equal(t2), nil
}
